# _*_coding:utf-8_*_

import time

from ATS.instrumentDriver import InstCom as inst
from ATS.datamanager.DataManager import DataManager



def sg_setup(source, ssetup):
    freq, pow, rf_out = ssetup
    inst.write(source, ':RAD:ARB:WAV "WFM1:2TONE_WFM"')
    inst.write(source, ':RAD:ARB ON')
    inst.write(source, 'OUTP:MOD ON')  # MODULATION ON
    inst.write(source, 'FREQ %s' % freq)
    #    print pow
    inst.write(source, 'POW %s' % pow)
    #    print rf_out
    inst.write(source, 'OUTP %s' % rf_out)
    time.sleep(0.1)


def toi_test(source='SS1', freq=3.5e9, space=1e6, pow=-20):
    ssetup = [freq, pow, 1]
    sg_setup(source, ssetup)

    span = space * 5
    sa_imdtest('SA1', freq, span)
    time.sleep(2)
    ssetup = [freq, pow, 0]
    sg_setup(source, ssetup)


def sa_imdtest(sa, x, span):
    inst.write(sa, 'CONF:TOI')
    inst.write(sa, 'FREQ:CENT %s' % x)

    inst.write(sa, ':TOI:FREQ:SPAN %s' % span)
    inst.write(sa, 'DISP:TOI:VIEW:WIND:TRAC:Y:RLEV 30')

    time.sleep(2)
    inst.write(sa, 'FETC:TOI?')
    time.sleep(0.5)
    str = inst.read(sa).split(',')
    #    print str
    buf = []
    buf.extend(str)
    print('%s dBm' % buf[-2])
    print('freq = %s' % buf[-1])

    buf1 = []
    buf2 = []
    buf1.append(buf[-1])
    buf2.append(buf[-2])

    DataManager().postarraydata('freq', buf1)
    DataManager().postarraydata('dBm', buf2)
    DataManager().postarraydata('Pass_Fail', '1')
